package com.yc.upload.web;

import com.yc.upload.vo.Result;
import com.yc.upload.vo.UploadProperties;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
public class UploadAction {

    @Resource
    UploadProperties properties;

    @RequestMapping("uploadProperties")
    public UploadProperties properties(){
        return properties;
    }

    // 127.0.0.1/upload/user
    @PostMapping("upload/{path}")
    public Result upload(@RequestParam("file") MultipartFile file,
                  @PathVariable String path) throws IOException {
        String diskPath = properties.getMapping().get(path);
        if(diskPath==null){
            return new Result(0,"没有映射对应的磁盘路径", path);
        } else {
            File dir = new File(diskPath);
            if(dir.exists() == false){
                // 创建多级文件夹
                dir.mkdirs();
            }
        }
        // 生成随机文件名 + 保留原文件后缀
        String filename = UUID.randomUUID().toString();
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.replaceAll(".+(\\.\\w+)","$1");
        filename += suffix;
        String filepath = diskPath + filename;
        // 保存文件
        file.transferTo(new File(filepath));
        // 返回上传文件的Web路劲
        String webPath = path + "/" + filename;
        return new Result(1,"文件上传成功!", webPath);
    }

    @PostMapping("uploads/{path}")
    public Result uploads(@RequestParam("file") MultipartFile[] files,
                   @PathVariable String path) throws IOException {
        List<String> paths = new ArrayList<>();
        for (MultipartFile file : files) {
            Result result = upload(file, path);
            paths.add((String) result.getData());
        }
        return new Result(1,"文件上传成功!", paths);
    }


}
